# LockNKey Quantum Service Dockerfile
# Multi-stage build for production-ready quantum cryptography service

# Build stage
FROM python:3.11-slim as builder

# Set build arguments
ARG BUILD_ENV=production

# Install system dependencies for building
RUN apt-get update && apt-get install -y \
    build-essential \
    gcc \
    g++ \
    cmake \
    libssl-dev \
    libffi-dev \
    pkg-config \
    && rm -rf /var/lib/apt/lists/*

# Set working directory
WORKDIR /app

# Copy requirements first for better Docker layer caching
COPY requirements.txt .

# Install Python dependencies
RUN pip install --no-cache-dir --user -r requirements.txt

# Production stage
FROM python:3.11-slim

# Set labels for container metadata
LABEL maintainer="LockNKey Team"
LABEL description="LockNKey Quantum Service - Post-quantum cryptography API"
LABEL version="1.0.0"

# Create non-root user for security
RUN groupadd --gid 1000 lockkey && \
    useradd --uid 1000 --gid lockkey --shell /bin/bash --create-home lockkey

# Install runtime dependencies
RUN apt-get update && apt-get install -y \
    libssl3 \
    ca-certificates \
    curl \
    && rm -rf /var/lib/apt/lists/* \
    && apt-get clean

# Set working directory
WORKDIR /app

# Copy Python packages from builder stage
COPY --from=builder /root/.local /home/lockkey/.local

# Ensure scripts in .local are usable
ENV PATH=/home/lockkey/.local/bin:$PATH

# Copy application code
COPY app/ ./app/
COPY requirements.txt .

# Create directories for logs and data
RUN mkdir -p /app/logs /app/data && \
    chown -R lockkey:lockkey /app

# Switch to non-root user
USER lockkey

# Set environment variables
ENV PYTHONPATH=/app
ENV PYTHONUNBUFFERED=1
ENV PYTHONDONTWRITEBYTECODE=1

# Health check
HEALTHCHECK --interval=30s --timeout=10s --start-period=60s --retries=3 \
    CMD python -c "import requests; requests.get('http://localhost:8001/health', timeout=5)"

# Expose port
EXPOSE 8001

# Default command
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8001", "--workers", "1"]